package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.adapter.base.recyler.ItemWrapper;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerAdapter;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerHolder;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.bean.MovieListBean;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.util.LogUtil;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MovieListFragment extends BaseFragment implements XRecyclerView.LoadingListener, View.OnClickListener {

    private XRecyclerView mRecyclerView;
    private RecyclerAdapter mRecylerAdapter;
    private ImageView backIv;
    private TextView titleTv,rightTv;

    private List<MovieListBean.DataBean.RecordsBean> mList;

    public static MovieListFragment newInstance(){
        MovieListFragment movieListFragment = new MovieListFragment();
        Bundle bundle = new Bundle();
        movieListFragment.setArguments(bundle);
        return movieListFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int setView() {
        return R.layout.fragment_movie;
    }

    @Override
    protected void init(View view) {
        backIv = view.findViewById(R.id.layout_head_back_iv);
        titleTv = view.findViewById(R.id.layout_head_title_tv);
        rightTv = view.findViewById(R.id.layout_head_right_tv);

        mRecyclerView = view.findViewById(R.id.movie_list_recyler);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setArrowImageView(R.mipmap.iconfont_downgrey);

        mRecyclerView
                .getDefaultRefreshHeaderView()
                .setRefreshTimeVisible(true);
        mRecyclerView.getDefaultFootView().setLoadingHint("自定义加载中提示");
        mRecyclerView.getDefaultFootView().setNoMoreHint("自定义加载完毕提示");
        mRecyclerView.setLimitNumberToCallLoadMore(1);
        mRecyclerView.setLoadingListener(this);

        mRecylerAdapter = new RecyclerAdapter<MovieListBean.DataBean.RecordsBean>(mItemListener) {
            @Override
            public ItemWrapper getItemHolder(int position) {
                return new ItemWrapper(R.layout.item_food, FoodAdapter.class);
            }
        };
        mRecyclerView.setAdapter(mRecylerAdapter);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        httpStoreInfo("深圳","坂田","电影院",1);
        backIv.setOnClickListener(this);
        titleTv.setText("电影院");
        rightTv.setVisibility(View.GONE);
    }


    /**
     * 请求店铺信息
     */
    private void httpStoreInfo(String cityName, String region, String category, int page) {
        HttpUtils.doGet(HttpContant.URL + HttpContant.StoreInfo
                        + "?cityName=" + cityName + "&&region=" + region + "&&category=" + category + "&&page=" + page
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("getCinemaList", response.body().string()));
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event) {
        switch (event.getCls()) {
            case "requestFail":
                TastyToast.makeText(getActivity(), "请求失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                break;
            case "getCinemaList":
                LogUtil.e("getCinemaList", event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        mList = new ArrayList<>();
                        MovieListBean movieListBean = new Gson().fromJson(event.getData().toString(), MovieListBean.class);
                        mList.addAll(movieListBean.getData().getRecords());
                        mRecylerAdapter.addAll(mList);
                        mRecylerAdapter.notifyDataSetChanged();
                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mRecyclerView != null) {
            mRecyclerView.destroy();
            mRecyclerView = null;
        }
    }


    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {

    }

    private OnItemListener mItemListener = new OnItemListener() {
        @Override
        public void onItemClick(View view, int position) {

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_head_back_iv:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
        }
    }

    interface OnItemListener {
        void onItemClick(View view, int position);
    }

    static class FoodAdapter extends RecyclerHolder<MovieListBean.DataBean.RecordsBean> {


        private OnItemListener mItemListener;
        private ImageView storeImg;
        private TextView nameTv, classTv, addressTv;

        public FoodAdapter(View itemView, OnItemListener listener) {
            super(itemView);

            mItemListener = listener;

            storeImg = itemView.findViewById(R.id.food_img);
            nameTv = itemView.findViewById(R.id.food_store_name);
            classTv = itemView.findViewById(R.id.food_class);
            addressTv = itemView.findViewById(R.id.food_address);
        }

        @Override
        public void onBindView(MovieListBean.DataBean.RecordsBean dataBean) {
            Glide.with(storeImg.getContext()).load(dataBean.getPhoto_urls()).asBitmap().error(R.mipmap.user_pic).placeholder(R.mipmap.user_pic).into(storeImg);
            nameTv.setText(dataBean.getName());
            String categories = "";
            for (int i = 0; i < dataBean.getCategories().size(); i++) {
                categories = categories+dataBean.getCategories().get(i)+"   ";
            }
            classTv.setText(categories);
            addressTv.setText(dataBean.getAddress());
        }
    }
}
